package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type ReqData struct {
	Name string `json:"name"`
	Age int `json:"age"`
}

func HttpPostReq(write http.ResponseWriter, request *http.Request) {
	fmt.Printf("[status] recv http request\n")

	if request.Method != "POST" {
		fmt.Printf("[status] request method %s not POST\n", request.Method)
		write.WriteHeader(500)
		return
	}

	// 防止ddos攻击

	// 读取请求
	req := ReqData{}
	bodyBytes, err := ioutil.ReadAll(request.Body)
	n := len(bodyBytes)
	if err = json.Unmarshal(bodyBytes[:n], &req); err != nil {
		fmt.Printf("[status] read body failed : %v\n", err)
		write.WriteHeader(500)
		return
	}

	// 检查token

	// 回复
	fmt.Printf("get msg : %s\n", string(bodyBytes[:n]))
	write.WriteHeader(200)
	write.Write([]byte("hellow lbs"))
}

func HttpGetPing(write http.ResponseWriter, request *http.Request) {
	if request.Method != "POST" {
		fmt.Printf("[status] request method %s not POST\n", request.Method)
		write.WriteHeader(500)
		return
	}

	bodyBytes, err := ioutil.ReadAll(request.Body)
	if err != nil {
		fmt.Printf("[status] read body failed\n")
		write.WriteHeader(500)
		return
	}
	write.WriteHeader(200)
	write.Write(bodyBytes)
	return
}

const (
	ListenAddress = "10.0.24.4:9292"
)

func main() {
	http.HandleFunc("/saas/info/spa/v1/point/trigger", HttpPostReq)
	http.HandleFunc("/ping", HttpGetPing)

	fmt.Println("start server : ", ListenAddress)
	err := http.ListenAndServe(ListenAddress, nil)
	if err != nil {
		fmt.Printf("Start http server failed : %v", err)
	}
	fmt.Println("ending...")
}